//
//  BQCakeView.m
//  饼状图
//
//  Created by baiqiang on 16/1/27.
//  Copyright © 2016年 baiqiang. All rights reserved.
//

#import "BQCakeView.h"

@implementation BQCakeViewLayer

- (instancetype)init
{
    self = [super init];
    if (self) {
        
        //配置阴影效果
        self.shadowColor = [UIColor grayColor].CGColor;
        self.shadowOffset = CGSizeMake(0, 1);
        self.shadowOpacity = 0.3;
    }
    return self;
}

- (void)completeAngleLayer:(BQCakeCharAngle)angle Radius:(CGFloat)radius {
    //1.配置路径变量
    CGMutablePathRef path = CGPathCreateMutable();
    //2.设置路径起始点
    CGPathMoveToPoint(path, NULL, radius, radius);
    //3.设置扇形大小
    CGPathAddArc(path, NULL, radius, radius, radius, angle.startAngle, angle.endAngle, NO);
    //4.闭合路径
    CGPathCloseSubpath(path);
    //5.配置路径
    self.path = path;
    //6.配置layer大小
    self.bounds = CGRectMake(0, 0, radius * 2, radius * 2);
    //7.释放对象
    CGPathRelease(path);
}

@end


@interface BQCakeView ()
{
    CGFloat _radius;
    CGFloat _offset;
    NSArray <UIColor *> *_colors;
    NSArray <NSNumber *> *_ratioes;
    NSMutableArray <BQCakeViewLayer *> *_layers;
    NSMutableArray <NSNumber *> *_tanRaioes;
    BQCakeViewLayer *_animationLayer;
    BOOL _hasAnimation;
}

@end

@implementation BQCakeView
- (instancetype)initWithCenter:(CGPoint)point Radius:(CGFloat)radius colors:(NSArray<UIColor *> *)colors Ratioes:(NSArray<NSNumber *> *)ratioes offset:(CGFloat)offset {
    BOOL falg = NO;
    if (colors.count == ratioes.count ) {
        falg = YES;
    }
    if (falg) {
        __block NSInteger sum = 0;
        [ratioes enumerateObjectsUsingBlock:^(NSNumber * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            sum += [obj floatValue];
        }];
        if (sum != 1) {
            falg = NO;
        }
    }
    NSAssert(falg == NO, @"ratioes数组元素和必须为1");
    self = [super init];
    if (self) {
        self.bounds = CGRectMake(0, 0, radius * 2, radius *2);
        self.center = point;
        _tanRaioes = [NSMutableArray array];
        _layers = [NSMutableArray array];
        _hasAnimation = NO;
        _radius = radius;
        _offset = offset;
        _colors = colors;
        _ratioes = ratioes;
    }
    return self;
}

- (void)willMoveToSuperview:(UIView *)newSuperview {
    [super willMoveToSuperview:newSuperview];
    
    BQCakeCharAngle angle = BQCakeCharAngleMake(0, 0);
    for (NSInteger i = 0; i < _colors.count;  ++i) {
        BQCakeViewLayer *layer = [BQCakeViewLayer layer];
        angle = BQCakeCharAngleMake(angle.endAngle, angle.endAngle + [_ratioes[i] doubleValue] * 2 * M_PI);
        
        //计算layer偏向移动角度
        layer.angle = (angle.startAngle + angle.endAngle) * 0.5;
        
        NSNumber *number = [NSNumber numberWithDouble:angle.endAngle];
        [_tanRaioes addObject:number];
        
        [layer completeAngleLayer:angle Radius:_radius - _offset];
        layer.fillColor = _colors[i].CGColor;
        layer.position = CGPointMake(_radius, _radius);
        [self.layer addSublayer:layer];
        [_layers addObject:layer];
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:self];
    if ([self isInCircel:point]) {
        
        BQCakeViewLayer *layer = [self clickedLayerWithPoint:point];
        
        if (_animationLayer != layer) {
            _hasAnimation = NO;
            [_animationLayer removeAllAnimations];
        }

        if (_hasAnimation == NO) {
            CABasicAnimation *animation = [CABasicAnimation animation];
            animation.keyPath = @"transform";
            animation.duration = 0.25;
            animation.fromValue = [NSValue valueWithCATransform3D:layer.transform];
            animation.toValue = [NSValue valueWithCATransform3D:CATransform3DTranslate(layer.transform, _offset * cos(layer.angle), _offset * sin(layer.angle), 0)];
            animation.byValue = [NSValue valueWithCATransform3D:CATransform3DScale(layer.transform, 1.1, 1.1, 1)];
            animation.removedOnCompletion = NO;
            animation.fillMode = kCAFillModeForwards;
            [layer addAnimation:animation forKey:nil];
            _hasAnimation = YES;
        }else {
            [_animationLayer removeAllAnimations];
            _hasAnimation = NO;
        }
        
        _animationLayer = layer;
    }
}

/**
 *  取得被点击的layer图层
 *
 *  @param point 点击位置
 */
- (BQCakeViewLayer *)clickedLayerWithPoint:(CGPoint)point {
    //获取点与中心点的夹角
    double tan = atan2(point.y - _radius, point.x - _radius);
    if (tan < 0) {
        tan += 2 * M_PI;
    }
    __block NSInteger index = 0;
    [_tanRaioes enumerateObjectsUsingBlock:^(NSNumber * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (tan > obj.doubleValue) {
            ++index;
        }
    }];
    
    BQCakeViewLayer *layer = _layers[index];
    
    return layer;
}
/**
 *  判断点击位置在圆形中
 *
 *  @param point 点击位置
 */
- (BOOL)isInCircel:(CGPoint)point {
    if (_radius - _offset >= sqrt(pow(point.x - _radius, 2) + pow(point.y - _radius, 2))) {
        return YES;
    }
    return NO;
}
@end
